<?php

namespace ua_backend\controllers;
include_once dirname(dirname(__FILE__)).'/../common/components/phpqrcode.php';

use Yii;
use ua_backend\models\Admin;
use ua_backend\models\search\AdminSearch;
use yii\helpers\Console;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use mdm\admin\components\AccessControl;
use yii\helpers\Json;
use yii\rbac\DbManager;

/**
 * UserController implements the CRUD actions for User model.
 */
class AdminController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [],
             ],
            'access' => [
                'class' => AccessControl::className(),
             ],

        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AdminSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $template = '{update} {delete}';

       //echo '123'.$template;die();
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'template' => $template,
        ]);
    }

    public function actionList()
    {
        $searchModel = new AdminSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $template = '{update} {delete}';

        //echo '123'.$template;die();
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'template' => $template,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    protected function findModel($id)
    {
        if (($model = Admin::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Admin();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->generateAuthKey();
            $model->auth_key = $model->getAuthKey();
            $model->setPassword($_POST['Admin']['password']);
            $model->created_at = $model->updated_at = time();

            if(isset($_POST['Admin']['role']) && $_POST['Admin']['role']==20){
                $model->role = 20;
            }else{
                $model->role = 30;
            }

            $model->code = $this->setCode();

            if($model->save()){
                $role = $model->role===20?'后台管理':'后台普通';
                $auth = new DbManager;
                $auth->init();
                $obj = $auth->getRole($role);
                $auth->assign($obj, $model->id);

                //生成同步数据二维码（本地数据到服务端）
//                $url = API.'wx/get-qrcode?dealer_code='.$model->code;
//                self::curl_get($url);
//
//                //生成同步数据二维码（小程序数据到本地）
//                $url = API.'wx/get-qrcode-from-app?dealer_code='.$model->code;
//                self::curl_get($url);
//
//                //生成销售登记二维码
//                $url = API.'wx/get-sale-qrcode?dealer_code='.$model->code;
//                self::curl_get($url);

                return $this->redirect(['list']);
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    protected function setCode(){
        $chars = Yii::$app->params['Chars'];
        $codes = '';
        for($i=0; $i<4; $i++){
            $codes .= $chars[mt_rand(0,35)];
        }

        $count = Admin::find()->where(['code'=>$codes])->count();
        if($count>0){ return $this->setCode(); }

        return $codes;
    }

    // 二维码

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $idv
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = Admin::findOne($id);
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $posts = $model->dirtyAttributes;
            $model->updated_at = time();

            //修改密码
//            $changePwd = false;
            if(isset($_POST['Admin']['password']) && $_POST['Admin']['password']!=$model->password_hash){
                $model->generateAuthKey();
                $model->auth_key = $model->getAuthKey();
                $model->setPassword($_POST['Admin']['password']);
//                $changePwd = true;
            }

            if(isset($_POST['Admin']['role']) && $_POST['Admin']['role']==20){
                $model->role = 20;
            }else{
                $model->role = 30;
            }
            $model->save();

            // 重新分配权限
            $role = $model->role===20?'后台管理':'后台普通';
            $auth = new DbManager;
            $auth->init();
            $obj = $auth->getRole($role);
            $auth->revokeAll($model->id);
            $auth->assign($obj, $model->id);

            return $this->redirect(['list']);


            //判断是否有修改数据，修改了就保存，否则不存
//            if($changePwd==true){
//                Yii::$app->session->set('update', 'succ');
//                $model->save();
//                return $this->render('update', ['model' => $model]);
//            }else{
//                $model->save();
//                Yii::$app->session->remove('update');
//                return $this->render('update', ['model' => $model]);
//            }

        } else {
            Yii::$app->session->remove('update');
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    // Curl Get 方法

    public function actionQrcode(){
        //生成同步数据二维码（小程序数据到本地）
        $url = API.'wx/get-qrcode-from-app?dealer_code='.$_GET['dealer_code'];
        self::curl_get($url);

        //生成销售登记二维码
        $url = API.'wx/get-sale-qrcode?dealer_code='.$_GET['dealer_code'];
        self::curl_get($url);

        //生成同步数据二维码（本地数据到服务端）
        $url = API.'wx/get-qrcode?dealer_code='.$_GET['dealer_code'];
        $data = self::curl_get($url);

        $obj = json_decode($data);
        $path = $obj->data->filepath;

        header('content-type:image/jpg;');
        $content=file_get_contents(UPLOAD_PATH.$path);

        echo $content;
    }

    protected function curl_get($url){
        $header = array('Accept: application/json');
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($curl);
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);
        } else {
            return $data;
            curl_close($curl);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateProfile($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->updated_at = time();
            if(isset($_POST['User']['password']) && $_POST['User']['password']!=''){
                $model->password = $model->setPassword($_POST['User']['password']);
            }
            $model->save();

            return $this->redirect(['profile']);
        } else {
            $action = Yii::$app->controller->action->id.$_GET['act'];
            return $this->render($action, [
                'model' => $model,
            ]);
        }
    }

    public function actionChangepwd($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->updated_at = time();
            $model->password = $model->setPassword($_POST['User']['password']);
            $model->save();
            return $this->redirect(['index']);
        } else {
            return $this->render('changepwd', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $user = $this->findModel($id);
        $auth = new DbManager;
        $auth->init();
        $auth->revokeAll($id);

        $user->delete();
        return $this->redirect(['list']);
    }

    public function actionProfile()
    {
        $id = Yii::$app->user->id;
        $model = Admin::findOne($id);
        return $this->render('profile', [
            'model' => $model
        ]);
    }

    public function actions()
    {
        return [
            'crop'=>[
                'class' => 'hyii2\avatar\CropAction',
                'config'=>[
                    'bigImageWidth' => '200',     //大图默认宽度
                    'bigImageHeight' => '200',    //大图默认高度
                    'middleImageWidth'=> '100',   //中图默认宽度
                    'middleImageHeight'=> '100',  //中图图默认高度
                    'smallImageWidth' => '50',    //小图默认宽度
                    'smallImageHeight' => '50',   //小图默认高度
                    //头像上传目录（注：目录前不能加"/"）
                    'uploadPath' => UPLOAD_PATH,
                    'model' => 'user',
                ],
            ]
        ];
    }

}
